package com.yunfeisoft.controller.business;

import com.applet.base.BaseController;
import com.applet.utils.*;
import com.yunfeisoft.business.model.Customer;
import com.yunfeisoft.business.model.IncomeRecord;
import com.yunfeisoft.business.model.SaleItem;
import com.yunfeisoft.business.model.SaleOrder;
import com.yunfeisoft.business.service.inter.*;
import com.yunfeisoft.model.User;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * ClassName: SaleOrderController
 * Description: 销售单信息Controller
 * Author: Jackie liu
 * Date: 2020-07-23
 */
@Controller
public class SaleOrderController extends BaseController {

    @Autowired
    private SaleOrderService saleOrderService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CodeBuilderService codeBuilderService;
    @Autowired
    private IncomeRecordService incomeRecordService;
    @Autowired
    private SaleItemService saleItemService;

    /**
     * 添加销售单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/save", method = RequestMethod.POST)
    @ResponseBody
    public Response save(SaleOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "customerId", "客户为空");
        validator.required(request, "saleDate", "销售日期为空");
        validator.number(request, "payAmount", "已收金额不合法");
        validator.required(request, "productsStr", "商品为空");
        validator.required(request, "submitType", "提交方式为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        User user = ApiUtils.getLoginUser();
        record.setId(KeyUtils.getKey());
        record.setOrgId(user.getOrgId());

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<SaleItem> saleItems = FastJsonUtils.jsonToList(productsStr, SaleItem.class);

        BigDecimal totalCostAmount = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;

        Iterator<SaleItem> iterator = saleItems.iterator();
        while (iterator.hasNext()) {
            SaleItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setSaleOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getQuantity() == null) {
                return ResponseUtils.warn("含有数量不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                item.setPrice(BigDecimal.ZERO);
                //return ResponseUtils.warn("含有进货价不合法或者为空的商品");
            }

            if (item.getSalePrice() == null) {
                item.setSalePrice(BigDecimal.ZERO);
                //return ResponseUtils.warn("含有售价不合法或者为空的商品");
            }

            if (item.getDiscount() == null) {
                return ResponseUtils.warn("含有折扣不合法或者为空的商品");
            }

            item.setAmount(item.getPrice().multiply(item.getQuantity()));
            item.setSaleAmount(item.getSalePrice().multiply(item.getQuantity()));

            totalCostAmount = totalCostAmount.add(item.getAmount());
            totalAmount = totalAmount.add(item.getSaleAmount());
        }
        record.setTotalCostAmount(totalCostAmount);
        record.setTotalAmount(totalAmount);
        record.setSaleItemList(saleItems);
        if (CollectionUtils.isEmpty(saleItems)) {
            return ResponseUtils.warn("商品为空");
        }

        String code = codeBuilderService.generateSaleOrderCode(user.getOrgId());
        record.setCode(code);

        String submitType = ServletRequestUtils.getStringParameter(request, "submitType", null);
        if ("settle".equals(submitType)) {//结清保存
            record.setStatus(SaleOrder.SaleOrderStatusEnum.DELIVERED.getValue());
            record.setPayStatus(SaleOrder.SaleOrderPayStatusEnum.RECEIVED.getValue());
            record.setPayAmount(totalAmount);

            IncomeRecord incomeRecord = new IncomeRecord();
            incomeRecord.setOrgId(user.getOrgId());
            incomeRecord.setCustomerId(record.getCustomerId());
            incomeRecord.setSaleOrderId(record.getId());
            incomeRecord.setReceiveAmount(totalAmount);
            incomeRecord.setIncomeAmount(record.getPayAmount());
            incomeRecord.setOutAmount(totalAmount.subtract(record.getPayAmount()));
            incomeRecord.setRemark("录单收款");
            record.setIncomeRecord(incomeRecord);
        } else if ("pay".equals(submitType)) {//收款保存
            record.setStatus(SaleOrder.SaleOrderStatusEnum.DELIVERED.getValue());
            record.setPayStatus(SaleOrder.SaleOrderPayStatusEnum.TO_BE_CLEARED.getValue());

            //设置收款记录
            record.setPayAmount(BigDecimal.ZERO);
        }

        saleOrderService.save(record);
        return ResponseUtils.success("保存成功", record.getId());
    }

    /**
     * 修改销售单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(SaleOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "id", "参数错误");
        validator.required(request, "customerId", "客户为空");
        validator.required(request, "saleDate", "销售日期为空");
        validator.number(request, "payAmount", "已收金额不合法");
        validator.required(request, "productsStr", "商品为空");
        validator.required(request, "submitType", "提交方式为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        User user = ApiUtils.getLoginUser();

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<SaleItem> saleItems = FastJsonUtils.jsonToList(productsStr, SaleItem.class);

        BigDecimal totalCostAmount = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        Iterator<SaleItem> iterator = saleItems.iterator();
        while (iterator.hasNext()) {
            SaleItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setSaleOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getQuantity() == null) {
                return ResponseUtils.warn("含有数量不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                item.setPrice(BigDecimal.ZERO);
                //return ResponseUtils.warn("含有进货价不合法或者为空的商品");
            }

            if (item.getSalePrice() == null) {
                item.setSalePrice(BigDecimal.ZERO);
                //return ResponseUtils.warn("含有售价不合法或者为空的商品");
            }

            if (item.getDiscount() == null) {
                return ResponseUtils.warn("含有折扣不合法或者为空的商品");
            }

            item.setAmount(item.getPrice().multiply(item.getQuantity()));
            item.setSaleAmount(item.getSalePrice().multiply(item.getQuantity()));

            totalCostAmount = totalCostAmount.add(item.getAmount());
            totalAmount = totalAmount.add(item.getSaleAmount());
        }
        record.setTotalCostAmount(totalCostAmount);
        record.setTotalAmount(totalAmount);
        record.setSaleItemList(saleItems);
        if (CollectionUtils.isEmpty(saleItems)) {
            return ResponseUtils.warn("商品为空");
        }

        String submitType = ServletRequestUtils.getStringParameter(request, "submitType", null);
        if ("settle".equals(submitType)) {//结清保存
            record.setStatus(SaleOrder.SaleOrderStatusEnum.DELIVERED.getValue());
            record.setPayStatus(SaleOrder.SaleOrderPayStatusEnum.RECEIVED.getValue());
            record.setPayAmount(totalAmount);

            IncomeRecord incomeRecord = new IncomeRecord();
            incomeRecord.setOrgId(user.getOrgId());
            incomeRecord.setCustomerId(record.getCustomerId());
            incomeRecord.setSaleOrderId(record.getId());
            incomeRecord.setReceiveAmount(totalAmount);
            incomeRecord.setIncomeAmount(record.getPayAmount());
            incomeRecord.setOutAmount(totalAmount.subtract(record.getPayAmount()));
            incomeRecord.setRemark("录单收款");
            record.setIncomeRecord(incomeRecord);
        } else if ("pay".equals(submitType)) {//收款保存
            record.setStatus(SaleOrder.SaleOrderStatusEnum.DELIVERED.getValue());
            record.setPayStatus(SaleOrder.SaleOrderPayStatusEnum.TO_BE_CLEARED.getValue());

            //设置收款记录
            record.setPayAmount(BigDecimal.ZERO);
        }

        saleOrderService.modify(record);
        return ResponseUtils.success("保存成功", record.getId());
    }

    /**
     * 查询销售单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response query(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        SaleOrder record = saleOrderService.load(id);
        if (record != null) {
            Customer customer = customerService.load(record.getCustomerId());
            record.setCustomerName(customer.getName());
            record.setCustomer(customer);

            List<SaleItem> saleItemList = saleItemService.queryBySaleOrderId(id);
            record.setSaleItemList(saleItemList);

            List<IncomeRecord> incomeRecordList = incomeRecordService.queryBySaleOrderId(id);
            record.setIncomeRecordList(incomeRecordList);
        }
        return ResponseUtils.success(record);
    }

    /**
     * 查询销售单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/querySingle", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response querySingle(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        SaleOrder record = saleOrderService.load(id);
        return ResponseUtils.success(record);
    }

    /**
     * 分页查询销售单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response list(HttpServletRequest request, HttpServletResponse response) {
        String customerName = ServletRequestUtils.getStringParameter(request, "customerName", null);
        int payStatus = ServletRequestUtils.getIntParameter(request, "payStatus", -1);

        User user = ApiUtils.getLoginUser();

        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("orgId", user.getOrgId());
        params.put("customerName", customerName);
        if (payStatus > 0) {
            params.put("payStatus", payStatus);
        }

        Page<SaleOrder> page = saleOrderService.queryPage(params);
        return ResponseUtils.success(page);
    }

    /**
     * 批量删除销售单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/saleOrder/delete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response delete(HttpServletRequest request, HttpServletResponse response) {
        String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
        if (StringUtils.isBlank(ids)) {
            return ResponseUtils.warn("参数错误");
        }
        String[] idArr = ids.split(",");
        saleOrderService.remove(idArr);
        return ResponseUtils.success("删除成功");
    }

}
